package com.example.multithreadserver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.wanhe.protocollibrary.ProtocolConst;
import com.wanhe.soserver.PSServer;
import com.wanhe.soserver.ServerConfig;

/*
 * @Author mowen
 * @Time 2013/6/9
 */

public class MainActivity extends Activity {

    public static final String TAG = "MainActivity";

    private static final int PORT = 9999;
    private List<Socket> mList = new ArrayList<Socket>();
    private volatile PSServer server = null;
    private ExecutorService mExecutorService = null; //�̳߳�
    private String hostip;//����IP
    private TextView mText1;
    private TextView mText2;
    private Button mBut1 = null;
    private Handler myHandler = null;
    private volatile boolean flag = true;//�̱߳�־λ

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        hostip = getLocalIpAddress();  //��ȡ����IP
        mText1 = (TextView) findViewById(R.id.textView1);
        mText1.setText(hostip);
        mText1.setEnabled(false);

        mText2 = (TextView) findViewById(R.id.textView2);

        mBut1 = (Button) findViewById(R.id.but1);


        server = PSServer.getInstance();
        server.init(ServerConfig.config().setPort(ProtocolConst.SOCKET_SERVER_PORT));
        server.addServerStateListener(new PSServer.OnServerStateListener() {
            @Override
            public void online() {
                Log.i(TAG, "online: ");
            }

            @Override
            public void offLine() {
                Log.i(TAG, "offLine: ");
            }

            @Override
            public void error(int errorState) {
                Log.i(TAG, "error: " + errorState);
            }
        });
        server.setMsgChangeListener(new PSServer.OnMsgChangeListener() {
            @Override
            public void receiveClientMsg(int type, String msg) {
                Log.i(TAG, "receiveClientMsg: " + msg);
                Message msgLocal = new Message();
                msgLocal.what = 0x1234;
                msgLocal.obj = msg + "(来自客户端)";
                myHandler.sendMessage(msgLocal);
            }

            @Override
            public void error(String error) {
                Log.i(TAG, "error: " + error);
            }
        });

        server.startSocketServer();     //����socket�����

        //ȡ�÷�UI�̴߳�����msg���Ըı����
        myHandler = new Handler() {
            @SuppressLint("HandlerLeak")
            public void handleMessage(Message msg) {
                if (msg.what == 0x1234) {
                    mText2.append("\n" + msg.obj.toString());
                }
            }
        };

        mBut1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                server.sendMsg(1, "服务端发送" + System.currentTimeMillis());
            }
        });

    }
//    //��button1�ļ����¼�
//	private final class Button1ClickListener implements View.OnClickListener{
//		@Override
//		public void onClick(View v) {
//			// TODO Auto-generated method stub
//			//����ǡ���������֤���������ǹر�״̬�����Կ���������
//			if(mBut1.getText().toString().equals("����")){
//
//			}else{
////				try {
////					flag=false;
////					server.close();
////					for(int p=0;p<mList.size();p++){
////					Socket s=mList.get(p);
////					s.close();
////					}
////					mExecutorService.shutdownNow();
////					mBut1.setText("����");
////					System.out.println("�������ѹر�");
////				} catch (IOException e) {
////					// TODO Auto-generated catch block
////					e.printStackTrace();
////				}
//
//			}
//
//		}
//	}

//    //Server�˵����߳�
//    class ServerThread extends Thread {
//
//        public void stopServer() {
//            try {
//                if (server != null) {
//                    server.close();
//                    System.out.println("close task successed");
//                }
//            } catch (IOException e) {
//                System.out.println("close task failded");
//            }
//        }
//
//        public void run() {
//
//            try {
//                server = new ServerSocket(PORT);
//            } catch (IOException e1) {
//                // TODO Auto-generated catch block
//                System.out.println("S2: Error");
//                e1.printStackTrace();
//            }
//            mExecutorService = Executors.newCachedThreadPool();  //����һ���̳߳�
//            System.out.println("������������...");
//            Socket client = null;
//            while (flag) {
//                try {
//                    System.out.println("S3: Error");
//                    client = server.accept();
//                    System.out.println("S4: Error");
//                    //�ѿͻ��˷���ͻ��˼�����
//                    mList.add(client);
//                    mExecutorService.execute(new Service(client)); //����һ���µ��߳�����������
//                } catch (IOException e) {
//                    System.out.println("S1: Error");
//                    e.printStackTrace();
//                }
//            }
//
//
//        }
//    }

    //��ȡIPv6��IP��ַ
    /*public String getLocalIpAddress() {
        try {  
            for (Enumeration<NetworkInterface> en = NetworkInterface  
                    .getNetworkInterfaces(); en.hasMoreElements();) {  
                NetworkInterface intf = en.nextElement();  
                for (Enumeration<InetAddress> enumIpAddr = intf  
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {  
                    InetAddress inetAddress = enumIpAddr.nextElement();  
                    if (!inetAddress.isLoopbackAddress()) {  
                        return inetAddress.getHostAddress().toString();  
                    }  
                }  
            }  
        } catch (SocketException ex) {  
            Log.e("WifiPreference IpAddress", ex.toString());  
        }  
        return null;  
    }  */
    //��ȡ����IP
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("WifiPreferenceIpAddress", ex.toString());
        }
        return null;
    }

//    //������client�Ի����߳�
//    class Service implements Runnable {
//        private volatile boolean kk = true;
//        private Socket socket;
//        private BufferedReader in = null;
//        private String msg = "";
//
//        public Service(Socket socket) {
//            this.socket = socket;
//            try {
//                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//                msg = "OK";
//                this.sendmsg(msg);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//        }
//
//        public void run() {
//
//            while (kk) {
//                try {
//                    if ((msg = in.readLine()) != null) {
//                        //���ͻ��˷��͵���ϢΪ��exitʱ���ر�����
//                        if (msg.equals("exit")) {
//                            mList.remove(socket);
//                            in.close();
//                            socket.close();
//                            break;
//                            //���տͻ��˷���������Ϣmsg��Ȼ���͸��ͻ��ˡ�
//                        } else {
//                            Message msgLocal = new Message();
//                            msgLocal.what = 0x1234;
//                            msgLocal.obj = msg + " ���ͻ��˷��ͣ�";
//                            System.out.println(msgLocal.obj.toString());
//                            System.out.println(msg);
//                            myHandler.sendMessage(msgLocal);
//                            msg = socket.getInetAddress() + ":" + msg + "�����������ͣ�";
//                            this.sendmsg(msg);
//                        }
//
//                    }
//                } catch (IOException e) {
//                    System.out.println("close");
//                    kk = false;
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//
//            }
//
//
//        }
//
//        //��ͻ��˷�����Ϣ
//        public void sendmsg(String msg) {
//            System.out.println(msg);
//            PrintWriter pout = null;
//            try {
//                pout = new PrintWriter(new BufferedWriter(
//                        new OutputStreamWriter(socket.getOutputStream())), true);
//                pout.println(msg);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }
}
